package com.ww.juc.threadpool.custom;

import java.util.Date;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 在使用自定义线程工厂时，线程如果出现异常完全可以自定义处理的
 *
 * @author wanggw
 * @date 2024-07-12 23:36:06
 */
public class TestDemo2 {

    public static void main(String[] args) {
        Runnable1 runnable1 = new Runnable1();
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, 9999, 9999, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        poolExecutor.setThreadFactory(new ThreadFactory2());
        poolExecutor.execute(runnable1);
        poolExecutor.shutdown();
    }
}

class ThreadFactory2 implements ThreadFactory {

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setName("新名字：" + new Date());
        thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("自定义处理异常启用：" + t.getName() + ", " + e.getMessage());
                e.printStackTrace();
            }
        });
        return thread;
    }
}

class Runnable2 implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "-" + System.currentTimeMillis());
        String abc = null;
        abc.indexOf(0);

    }
}